<script setup lang="ts">
import Content from '@/components/Content/index.vue'
import ContentTitle from '@/components/ContentTitle/index.vue'
import APIOrder from '@/api/order'
import { Edit, ArrowRightBold } from '@element-plus/icons-vue'
import { type FormRules, type FormInstance, ElMessage } from 'element-plus'
import { downloadFile, chunkUplaod, getFileNameFromUrl } from '@/utils/index'
import APIStoreHome from '@/api/store-home'
import { ElMessageBox, ElLoading } from 'element-plus'
import { useAuth } from '@/stores/index'
import SelfPagination from '@/components/SelfPagination/index.vue'
import { replaceCommaWithDash } from '@/utils/index'

const { info, token } = storeToRefs(useAuth())

const queryParams = ref<PageQuery>({
    page: 1,
    limit: 8
})

const list = ref([])
const total = shallowRef<number>(0)

const loading = shallowRef<boolean>(false)

function getList() {
    loading.value = true
    APIOrder.getOrderGoods(queryParams.value).then(({ data, total: count }) => {
        list.value = data
        total.value = count
    }).finally(() => {
        loading.value = false
    })
} getList()

const dialogVisible = shallowRef<boolean>(false)

const innterVisible = shallowRef<boolean>(false)

const formData = ref<any>({})
const rules = reactive<FormRules<any>>({
    authorize_name: [
        { required: true, message: '请输入被授权名字（或公司）', trigger: 'blur' },
    ],
    authorize_code: [
        { required: true, message: '请输入身份证（或信用代码）', trigger: 'blur' },
    ],
})

const ruleFormRef = ref<FormInstance>()

function submitSetAuthCertificate() {
    ruleFormRef.value?.validate((valid) => {
        if (valid) {
            const form = { ...formData.value }
            form.order_code = goodsInfo.value.order_code
            APIOrder.setAuthCertificate(form).then(({ msg }) => {
                ElMessage.success(msg)
                innterVisible.value = false
                getList()
            })
        }
    })
}
const goodsInfo = ref<any>({})

function handleShow(row: any) {
    goodsInfo.value = row
    dialogVisible.value = true
}

function onBeforeClose() {
    formData.value = {}
    goodsInfo.value = {}
    isDownload.value = false
    percentage.value = 0
    dialogVisible.value = false
}

const isDownload = shallowRef<boolean>(false)
const percentage = shallowRef<number>(0)

function throttle<T extends (...args: any[]) => any>(func: T, delay: number): T {
    let lastCall = 0;
    return function (...args: Parameters<T>): void {
        const now = Date.now();
        if (now - lastCall >= delay) {
            lastCall = now;
            func(...args);
        }
    } as T;
}

// 创建一个节流的函数
const throttledUpdate = throttle(() => {
    ElMessage.success('下载成功')
    onBeforeClose()
}, 2000); // 设置节流间隔为1000ms

watch(percentage, (newValue) => {
    if (newValue == 100) {
        throttledUpdate()
    }
})

function handleDownload() {

    const { goods_type, file, is_template, title, project_file, goods_code } = goodsInfo.value

    const suffix = file.split('.').at(-1)
    if (goods_type == 'video') {
        isDownload.value = true
        chunkUplaod(file, `心安元素_${goods_code}.${suffix}`, (progress: any) => {
            if (Number(progress) >= 100 && percentage.value != 100) {
                percentage.value = 100
            } else {
                percentage.value = Number(progress)
            }
        })
        if (is_template == 1) {
            const projectFileSuffix = project_file.split('.').at(-1)

            downloadFile(project_file, `心安元素_${goods_code}.${projectFileSuffix}`)
        }
    } else if (goods_type == 'picture') {
        isDownload.value = true
        percentage.value = 100
        downloadFile(file, `心安元素_${goods_code}.${suffix}`)
    } else if (goods_type == 'music') {
        isDownload.value = true
        chunkUplaod(file, `心安元素_${goods_code}.${suffix}`, (progress: any) => {
            if (Number(progress) >= 100) {
                percentage.value = 100
            } else {
                percentage.value = Number(progress)
            }
        })
    } else if (goods_type == 'font') {
        isDownload.value = true
        percentage.value = 100
        downloadFile(file, `心安元素_${goods_code}.${suffix}`)
    }
}


const drawer = shallowRef<boolean>(false)

function handleClose() {
    drawer.value = false
}


const orderInfo = ref<any>({})


function handleShowDrawer(row: any) {
    drawer.value = true

    const queryData = {
        order_id: row.order_id,
        goods_type: row.goods_type,
        type: row.type,
        goods_id: row.goods_id,
    }

    APIOrder.getOrderInfo(queryData).then(({ data }) => {
        orderInfo.value = data
    })
}

function submitAttention() {
    ElMessageBox.confirm(
        '是否关注该店铺？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        if (!orderInfo?.value?.user?.Invite_code) return
        const loading = ElLoading.service({ lock: true })
        APIStoreHome.setUserConcern(orderInfo?.value?.user?.Invite_code).then(() => {
            orderInfo.value.user.is_concern = 1
        }).finally(() => {
            loading.close()
        })
    }).catch(() => {
        ElMessage.info('已取消')
    })
}

function submitUnfollow() {
    ElMessageBox.confirm(
        '是否取消关注该店铺？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        if (!orderInfo?.value?.user?.Invite_code) return
        const loading = ElLoading.service({ lock: true })
        APIStoreHome.cancelUserConcern(orderInfo?.value?.user?.Invite_code).then(() => {
            orderInfo.value.user.is_concern = 0
        }).finally(() => {
            loading.close()
        })
    }).catch(() => {
        ElMessage.info('已取消')
    })
}

</script>

<template>
    <div class="order">
        <Content class="content">
            <ContentTitle title="订单信息"
                content="1、购买的订单里可以给订单进行完善授权（也就是确权，使用主体是哪一个）；<br />2、完善授权后的主体（个人/公司）可以更好的为您保驾护航，建议在下载资源前进行完善；<br />3、提交的授权信息系统将会固定后用于授权的确定和查询；" />
            <el-table class="list" :data="list" :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
                v-loading="loading">
                <el-table-column prop="order_code" label="订单" width="220" />
                <el-table-column label="缩略图" v-slot="{ row }">
                    <el-image style="width: 80px; height: 53px" :src="row.main_image"
                        :preview-src-list="[row.main_image]" fit="cover" :z-index="999" preview-teleported
                        hide-on-click-modal />
                </el-table-column>
                <el-table-column prop="type_name" label="类型" />
                <el-table-column prop="consum_name" label="消费类型" />
                <el-table-column prop="price" label="价格" />
                <el-table-column prop="create_time" label="购买时间" />
                <el-table-column label="授权信息 | 授权主体" v-slot="{ row }">
                    <span v-if="row.authorize_name && row.authorize_code">
                        {{ row.authorize_name }} | {{ row.authorize_code }}
                    </span>
                    <span v-else>暂无信息</span>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="{ row }">
                        <el-button class="btn" type="primary" v-if="row.type == 'goods_consum'" link
                            @click="handleShow(row)">下载</el-button>
                        <el-button class="btn" type="info" link @click="handleShowDrawer(row)">详情<el-icon>
                                <ArrowRightBold />
                            </el-icon></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <SelfPagination style="margin-top: 50px;margin-right: 30px;" :total="total"
                v-model:current-page="queryParams.page" :page-size="queryParams.limit" @get-list="getList" />
        </Content>
        <el-dialog v-model="dialogVisible" title="完善授权信息" width="600" :before-close="onBeforeClose" :show-close="false">
            <template #header>
                <DialogClose title="完善授权信息" @close="onBeforeClose" />
            </template>
            <el-dialog v-model="innterVisible" title="完善授权信息" width="600" :show-close="false">
                <template #header>
                    <DialogClose title="完善授权信息" @close="innterVisible = false" />
                </template>
                <el-form ref="ruleFormRef" :model="formData" :rules="rules" class="demo-ruleForm">
                    <el-form-item label="被授权名字（或公司）" prop="authorize_name">
                        <el-input v-model="formData.authorize_name" placeholder="请输入被授权名字（或公司）" />
                    </el-form-item>
                    <el-form-item label="身份证（或信用代码）" prop="authorize_code">
                        <el-input v-model="formData.authorize_code" placeholder="身份证（或信用代码）" />
                    </el-form-item>
                    <el-form-item>
                        <button type="button" class="btnsss" @click="submitSetAuthCertificate">
                            完善授权信息（不能更改）
                        </button>
                    </el-form-item>
                </el-form>
            </el-dialog>
            <div class="dialog-btn">
                <button type="button" @click="innterVisible = true">添加（完善）授权信息</button>
                <el-button type="danger" @click="handleDownload" :disabled="isDownload">下次再完善授权（直接下载）</el-button>
                <el-progress :percentage="percentage" v-show="isDownload" />
            </div>
        </el-dialog>
        <el-drawer v-model="drawer" title="订单详情" direction="rtl" :size="1040" :before-close="handleClose" destroy-on-close>
            <div class="order-details">
                <div class="mask">
                    <video v-if="orderInfo?.order?.type == 'video'" controls :src="orderInfo?.goods?.sample"
                        :poster="orderInfo?.goods?.image"></video>
                    <img class="picture" v-if="orderInfo?.order?.type == 'picture'" :src="orderInfo?.goods?.image" />
                    <img class="picture" v-if="orderInfo?.order?.type == 'music'" :src="orderInfo?.goods?.image" />
                    <img class="picture" v-if="orderInfo?.order?.type == 'font'" :src="orderInfo?.goods?.image" />
                </div>
                <div class="info">
                    <div class="title">基本信息：</div>
                    <div class="info-item">
                        <div class="info-item-label">类 型：</div>
                        <div class="info-item-value">
                            {{ orderInfo?.goods?.type_name }}
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-label">编 号：</div>
                        <div class="info-item-value">{{ orderInfo?.goods?.goods_code }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-label">标 题：</div>
                        <div class="info-item-value">{{ orderInfo?.goods?.title }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-label">格 式：</div>
                        <div class="info-item-value">{{ orderInfo?.goods?.format }}</div>
                    </div>
                    <div class="info-item" v-if="orderInfo?.goods?.width">
                        <div class="info-item-label">分 辨 率：</div>
                        <div class="info-item-value">{{ orderInfo?.goods?.width }} *{{ orderInfo?.goods?.height }}
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-label">大 小：</div>
                        <div class="info-item-value">{{ orderInfo?.goods?.file_size }}</div>
                    </div>
                </div>
                <div class="info">
                    <div class="title">授权信息：</div>
                    <div class="info-item">
                        <div class="info-item-label">授权编号：</div>
                        <div class="info-item-value">{{ orderInfo?.order?.auth_code || '暂无' }}</div>
                    </div>
                </div>
                <div class="info">
                    <div class="title">订单信息：</div>
                    <div class="info-item">
                        <div class="info-item-label">订单编号：</div>
                        <div class="info-item-value">{{ orderInfo?.order?.order_code }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-label">订单时间：</div>
                        <div class="info-item-value">{{ orderInfo?.order?.create_time }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-label">付款时间：</div>
                        <div class="info-item-value">{{ orderInfo?.order?.create_time }}</div>
                    </div>
                    <div class="info-item" v-if="orderInfo?.order?.using_body">
                        <div class="info-item-label">使用主体：</div>
                        <div class="info-item-value">{{ orderInfo?.order?.using_body }}</div>
                    </div>
                    <div class="info-item" v-if="orderInfo?.order?.auth_type">
                        <div class="info-item-label">授权类型：</div>
                        <div class="info-item-value">{{ orderInfo?.order?.auth_type }}</div>
                    </div>
                    <div class="info-item" v-if="orderInfo?.order?.auth_detail">
                        <div class="info-item-label">授权详情：</div>
                        <div class="info-item-value">{{ orderInfo?.order?.auth_detail }}</div>
                    </div>
                    <div class="info-item" v-if="orderInfo?.order?.auth_duration">
                        <div class="info-item-label">授权时长：</div>
                        <div class="info-item-value">{{ orderInfo?.order?.auth_duration }}</div>
                    </div>
                </div>
                <div class="info" v-if="orderInfo?.user">
                    <div class="title">卖方信息：</div>
                    <div class="info-item">
                        <div class="info-item-label">用户名：</div>
                        <div class="info-item-value">{{ orderInfo?.user?.username }}</div>
                        <div class="concern">
                            <button v-if="orderInfo?.user?.is_concern == 0" @click="submitAttention">+关注</button>
                            <button v-else-if="orderInfo?.user?.is_concern == 1" type="button"
                                style="background-color: #9499a0;" @click="submitUnfollow">已关注</button>
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-label">实名：</div>
                        <div class="info-item-value">{{ orderInfo?.user?.auth_info?.real_name }}<span
                                v-if="orderInfo?.user?.user_type == 'personal'">（个人）</span><span
                                v-if="orderInfo?.user?.user_type == 'company'">（公司）</span>{{
                                    orderInfo?.user?.auth_info?.id_card
                                }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-label">账号ID：</div>
                        <div class="info-item-value">{{ orderInfo?.user?.Invite_code }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-item-label">IP所在：</div>
                        <div class="info-item-value">{{ replaceCommaWithDash(orderInfo?.user?.area) }}</div>
                    </div>
                </div>
                <div v-else class="info">
                    <div class="title">卖方信息：</div>
                    <div class="info-item">
                        <div class="info-item-label">公司：</div>
                        <div class="info-item-value">湖南心安元素数字科技有限公司</div>
                    </div>
                </div>
            </div>
        </el-drawer>
    </div>
</template>

<style lang="scss">
.order {
    .list {
        .el-table__row {
            font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
        }

        .cell {
            font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
        }

        .btn {
            font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
        }
    }
}
</style>

<style lang="scss" scoped>
.order-details {
    width: 1000px;
    display: flex;
    flex-wrap: wrap;
    gap: 50px 50px;

    .info {
        width: 300px;
        display: flex;
        flex-direction: column;
        gap: 15px 0;

        .info-item {
            display: flex;

            .info-item-label {
                color: rgba(16, 16, 16, 1);
                font-size: 14px;
                white-space: nowrap;
                font-family: 'SOURCEHANSANSCN-LIGHT';
            }

            .info-item-value {
                color: rgba(16, 16, 16, 1);
                font-size: 14px;
                font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
            }

            .concern {
                margin-left: 20px;

                button {
                    width: 50px;
                    height: 20px;
                    display: block;
                    line-height: 20px;
                    border-radius: 5px;
                    border: none;
                    cursor: pointer;

                    &:first-child {
                        background-color: rgba(238, 239, 240, 1);
                        color: rgba(187, 187, 187, 1);
                        font-size: 12px;
                    }

                    &:last-child {
                        background-color: rgba(249, 20, 20, 1);
                        color: rgba(255, 255, 255, 1);
                        font-size: 12px;
                    }
                }
            }

        }

        .title {
            color: rgba(16, 16, 16, 1);
            font-size: 14px;
            font-weight: 700;
            display: flex;
            align-items: center;
            font-family: 'SOURCEHANSANSCN-REGULAR';

            &::before {
                content: '';
                display: block;
                width: 5px;
                height: 16px;
                border-radius: 5px;
                background-color: rgba(249, 20, 20, 1);
                margin-right: 4px;
            }
        }
    }

    .mask {
        width: 300px;
        height: 300px;
        background-color: rgba(218, 235, 254, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;

        .picture {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }

        video {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }
    }

}

.order {
    .btnsss {
        width: 231px;
        height: 40px;
        border-radius: 5px;
        background-color: rgba(15, 64, 245, 1);
        color: rgba(255, 255, 255, 1);
        font-size: 14px;
        border: none;
        cursor: pointer;
        margin-left: 163px;
        margin-top: 30px;
    }

    .dialog-btn {
        display: flex;
        flex-direction: column;
        gap: 34px 0;
        padding-bottom: 20px;
        align-items: center;

        button {
            width: 307px;
            height: 44px;
            border-radius: 5px 5px 5px 5px;
            background-color: rgba(220, 221, 221, 1);
            color: rgba(136, 136, 136, 1);
            font-size: 14px;
            border: none;
            cursor: pointer;
            transition: all .2s;

            &:hover {
                color: #ffffff;
                background-color: #1684FC;
            }
        }
    }

    .content {
        margin-bottom: 30px;

        .list {
            width: 99.99%;
            margin: 0 auto;
            margin-top: 30px;
        }
    }
}
</style>
